import time
import platform
import numpy as np
from . import gpio


class Servo():
    def __init__(self,config):
        super().__init__()
        self.data=[]
        self.deg=0
        self.config=config
        self.start_time = time.time()
        pass

    def append(self,duty):
        if (duty==65535):return
        self.data.append(duty)
        if round(time.time()-self.start_time,0)<0.5:return -1
        self.start_time = time.time()
        return self.compute()
    
    def compute(self):
        data=np.array(self.data)
        if np.std(data)==0: return -1
        z_scores = np.abs((data - np.mean(data))/np.std(data))
        duty =  np.mean(data[z_scores < 20])
        duty = abs(self.config["deg"]-((duty)/(self.config["max"]-self.config["min"]))*180)
        deg = round(2.5+(duty/180)*10, 1)
        self.data.clear()
        if abs(deg-self.deg)>0.3 and abs(deg-self.deg)<100:
            self.deg=deg
            return deg
        return -1
